var util = require('../../utils/util');
var wxApi = require('../../utils/wxApi');
var wxRequest = require('../../utils/wxRequest');
import config from '../../utils/config';

import {$wuxToptips} from '../../components/wux';
import WxValidate from '../../assets/plugins/WxValidate';
// import { $wuxXnumber } from '../../components/wux';
import { $wuxDialog } from '../../components/wux';

var WxParse = require('../../wxParse/wxParse.js');

var app = getApp();
var that,wxbjdays;

var _nowdate = new Date();
var strdate = util.formatTime(_nowdate);
var strtime = strdate.substr(11);
strdate = strdate.substr(0,10);

//获取应用实例
var app = getApp()
Page({
  data: {
    user: {},
    nowdate:_nowdate,
    form: {
      name: "", 
      issecret: 0, 
      pwd: '', 
      bdate: strdate, 
      edate: strdate, 
      ldate: strdate, 
      award: "",
      remark: "",
      bjdays: 1,  
      awardnum: 0, 
      time:strtime,
      key:"",

      qdlat:"",
      qdlng:"",
      zdlat:"",
      zdlng:"",
      btime:"",
      etime:"",
      jdate:strdate,
      qdname:"",
      qdaddr:"",
      zdname:"",
      zdaddr:"",
      dura:"",
      zddura:"",
      type:0
    },

    issecret: [
      {
        name: '公开', 
        value: 0, 
        checked: true, 
      },
      {
        name: '隐私', 
        value: 1, 
      }
    ],
    tid:0,
    indexdura:0,
    indexzddura:0,
    arrdura:[
         '25米', '50米', '100米', '200米'
    ],
    arrzddura:[
       '25米', '50米', '100米', '200米'
    ],
    indextype:0,
    arrtype:[
        {value: '0', name: '步数竞赛', checked: true },
        {value: '1', name: '速度竞赛'}
    ],
    input: '',
    todos: [
      // {name:"xxxx",id:"1"}
      // ,{name:"yyyy",id:"2"}
    ],
    curindex:-1
    ,sheight:450
    ,sheight2:450*0.2
  },
  onLoad: function (options) {
    that = this;

    wx.setNavigationBarTitle( { title: "竞赛信息编辑" });

     wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sheight: res.windowHeight,
          sheight2:res.windowHeight *0.15
        })
      }
    })
    
     if( !util.judge.isNull( options.tid) ){
         that.data.tid = parseInt(options.tid);
         that.setData({
             tid: options.tid
         });
     }else{
         that.setData({
             tid: 0
         });
     }

    if(util.judge.isString(options.key) ){
        that.data.key = options.key;
    }

    //if(util.judge.isString(options.type) ){
    //    that.setData({
    //        'form.type': options.type
    //    })
    //}else{
        
    //}

    this.setData({
        'form.type': 0,
        'form.dura': that.data.arrdura[2],
        'form.zddura': that.data.arrdura[0]
    })

    // wxbjdays = $wuxXnumber.init('bjdays', {
    //   min: 1, 
    //   max: 3, 
    //   value: 1 ,
    //   callback: (value) => that.setData({
    //     'form.bjdays': value
    //   }), 
    // });

    that.initValidate();
    //util.alert(that.data.tid);
    that.loadData();

  },
  loadData: function () {
    util.showLoading();
    app.getUserInfo()
    .then(res => {
      that.setData({
        user:res
      });

      if(that.data.user.isadmin==1){
          var d = {value: '2', name: '点对点'};
          that.data.arrtype.push(d);
          that.setData({arrtype:that.data.arrtype});
      }

      var url = config.url_get_yd_dk_txt;

      var params = {type:"team_create_remark"}

      return wxRequest.postRequest(url, params);
    })
    .then(res=>{
        if(util.judge.isObject(res)){
            var article =res.txt1;
            WxParse.wxParse('article', 'html', article, that, 0);
            WxParse.wxParse('article_js', 'html',  res.txt2, that, 0);
        }
         

      if(that.data.tid == 0){
        throw util.stop();
      }

      var url = config.url_team_get;
      var params = {
          id:that.data.tid
          ,code:'all'
      }
      return wxRequest.postRequest(url, params)
    })
    .then(res => {
        if(res.type==1){
            res.jdate = util.date2str(res.bdate,"yyyy-MM-dd");
            res.btime = util.date2str(res.bdate,"HH:mm");
            res.etime = util.date2str(res.edate,"HH:mm");
            res.dura =res.dura+"米";
            res.zddura =res.zddura+"米";
             
        }else{
            res.bdate = util.date2str(res.bdate,"yyyy-MM-dd");
            res.edate = util.date2str(res.edate,"yyyy-MM-dd");
        }

        var items = that.data.arrtype;
        for (var i = 0, len = items.length; i < len; ++i) {
            if(items[i].value == res.type){
                res.typetext = items[i].name;
            }
        }
        
        if(res.pwd =="n"){
          res.pwd ="";
        }
        
        // res.time = util.date2str(res.ldate,"HH:mm");
        // res.ldate = util.date2str(res.ldate,"yyyy-MM-dd");

        that.setData({form:res});

        // that.bindissecret({detail:{value:res.issecret}});
        // wxbjdays.updateValues(res.bjdays);

        
    })
    .then(res=>{
        
        var url = config.url_team_group;
        var params = {
            id:that.data.tid
        }
        return wxRequest.postRequest(url, params)
    })
    .then(res => {
      if(util.judge.isArray(res)){
        that.setData({
          todos:res
        });
      }
    })
    .catch(res => {
      util.alert_catch(res.message);
    })
    .finally(function (res) {
        util.hideLoading();
    });
  },
  showToptips(error) {
    const hideToptips = $wuxToptips.show({
      timer: 3000,
      text: error.msg || '请填写正确的字段',
      success: () => console.log('toptips', error)
    })
  },
  submitForm(e) {
    const data = e.detail.value
    var fid = e.detail.formId;
    // console.log(params)

    if (!this.WxValidate.checkForm(e)) {
      const error = this.WxValidate.errorList[0]
      this.showToptips(error)
      return false
    }

    if(util.judge.isString(data.pwd) && data.pwd.length > 0 ){
        if(data.pwd.length != 6){
            util.alert("密码长度为6位数字");
            return false;
        }
        var re = /^\d+$/;
        if(!re.test(data.pwd)){
            util.alert("密码必须为数字");
            return false;
        }
    }

    
    if(that.data.form.type ==1){
        if(that.data.form.btime.length==0){
            util.alert("请选择开始时间");
            return false;
        }

        if(that.data.form.etime.length==0){
            util.alert("请选择结束时间");
            return false;
        }

        if(that.data.form.qdlat.length==0){
            util.alert("请选择起点");
            return false;
        }

        if(that.data.form.zdlat.length==0){
            util.alert("请选择终点");
            return false;
        }
    }else{
        //日期不要超过90天
        var day = that.DateDiff(that.data.form.bdate,that.data.form.edate);
        if(day>90){
            util.alert("竞赛时间能大于90天");
            return false;
        }
    }



    var group = JSON.stringify(that.data.todos);

    // util.alert(group);
    // return false;

    util.showLoading();
    var url = config.url_team_edit;
    data.id =that.data.tid;

    data.key = that.data.key;
    if(!util.judge.isString(data.key) ){
      data.key = "";
    }
    data.group = group;
    data.fid=fid;
    var params = data;
    data.type = that.data.form.type;

    if(that.data.form.type==1){
        data.bdate = that.data.form.jdate +" "+that.data.form.btime;
        data.edate = that.data.form.jdate +" "+that.data.form.etime;
    }

    if(that.data.form.type==1 || that.data.form.type==2){

        data.qdlat = that.data.form.qdlat;
        data.qdlng = that.data.form.qdlng;
        data.qdaddr = that.data.form.qdaddr;
        data.qdname = that.data.form.qdname;

        data.zdlat = that.data.form.zdlat;
        data.zdlng = that.data.form.zdlng;
        data.zdaddr = that.data.form.zdaddr;
        data.zdname = that.data.form.zdname;

        data.dura = that.data.form.dura.toString().replace("米","");
        data.zddura = that.data.form.zddura.toString().replace("米","");
    }

    

    wxRequest.postRequest(url, params)
    .then(res => {
        console.log(res);
        that.data.tid = res.team.id;

        that.setData({
          todos:res.group
        });

        util.alert("提交成功",function(){
          var pages = getCurrentPages();
          that.data.prevPage = pages[pages.length - 2];
          if( that.data.prevPage.route.indexOf("ktlist") == -1 ){
            wx.redirectTo({
                url: '../user/ktlist_js'
            })
          }else{
            that.data.prevPage.onPullDownRefresh();
            wx.navigateBack({
            delta: 1
           })
          }
        });
    })
    .catch(res => {
        console.log(res);
        util.alert_catch(res.message);
    })
    .finally(function (res) {
        util.hideLoading();
    });

  },
  initValidate() {
      this.WxValidate = new WxValidate(
        {
        name: {
          required: true, 
        },
        //bdate: {
        //  required: true, 
        //},
        //edate: {
        //  required: true, 
        //},
        remark: {
            required: true, 
        },
        // award: {
        //   required: true, 
        // },
        // awardnum: {
        //   required: true, 
        // },
      }
      , 
      {
         name: {
          required: "请输入竞赛名称", 
        },
        //bdate: {
        //  required: "请输入开始时间", 
        //},
        //edate: {
        //  required: "请输入结束时间", 
        //},
        remark: {
            required: "请输入比赛公告", 
        },
        // ldate: {
        //   required: "请输入提交步数截止时间", 
        // },
        // award: {
        //   required: "请输入奖品", 
        // },
        // awardnum: {
        //   required: "请输入获奖人数", 
        // },
      }
    );
  },
  bindbdate: function(e) {
    this.setData({
      'form.bdate': e.detail.value
    })
  },
  bindedate: function(e) {
    this.setData({
      'form.edate': e.detail.value
    })
  },
  bindldate: function(e) {
    this.setData({
      'form.ldate': e.detail.value
    })
  },
  bindtime: function(e) {
    this.setData({
      'form.time': e.detail.value
    })
  },

  bindjdate: function(e) {
      this.setData({
          'form.jdate': e.detail.value
      })
  },

  bindetime: function(e) {
      this.setData({
          'form.etime': e.detail.value
          ,'form.bdate': strdate
      })
  },

  bindbtime: function(e) {
      this.setData({
          'form.btime': e.detail.value
          ,'form.edate': strdate
      })
  },

  bindawardnum: function (e) {
    this.setData({
      'form.awardnum': e.detail.value
    })
  },
  bindissecret:function (e) {
    var value =  e.detail.value;
    const issecret = this.data.issecret;
    issecret.forEach(n => n.checked = n.value == value)
    this.setData({
      issecret: issecret, 
      'form.issecret': value, 
    })
  },


  inputChangeHandle: function (e) {
    this.setData({input: e.detail.value})
  },

  editTodo: function (e) {
    if (!this.data.input || !this.data.input.trim()) {
      return
    }
    var todos = this.data.todos;
    var curindex = this.data.curindex;
    if(curindex > -1){
      todos[curindex].name = this.data.input;
    }else{
      todos.push({
        name: this.data.input,
        id: 0
      })
    }
     
    this.setData({
      todos: todos 
    })
 
  },
  toggleTodoHandle: function (e) {
    let index = e.currentTarget.dataset.index
    var todos = this.data.todos

    for (var i = 0; i < todos.length ; i++) {
      if(i!=index){
        todos[i].completed = false;
      }
    }
    
    todos[index].completed = !todos[index].completed;
    
    var curindex = -1;
    var sinput ="";
    if (todos[index].completed){
      curindex = index;
      sinput = todos[curindex].name;
    }
    this.data.curindex = curindex;

    this.setData({
      todos: todos,
      input:sinput
    })
 
  },
  open: function(e){
    let index = e.currentTarget.dataset.index;

    wx.showActionSheet({
        itemList: ['修改小组信息', '删除小组'],
        success: function(res) {
            
            if(res.tapIndex==1){
                let todos = that.data.todos
                var gid  = todos[index].id;
                $wuxDialog.confirm({
                  title: '确定删除组名吗?', 
                  content: '删除后将不能恢复!', 
                  onConfirm(e) {
                    if( gid > 0){
                      util.showLoading();
                      var url = config.url_group_del;
                      
                      var params = {
                        id:gid
                      };
                      wxRequest.postRequest(url, params)
                      .then(res => {

                          if(res == 21){
                            util.alert("组内有成员存在，不能删除！");
                            return false;
                          }

                          util.alert("删除成功",function(){
                            let remove = todos.splice(index, 1)[0];

                            that.setData({
                              todos: todos
                            })

                            if(index == that.data.curindex){
                              that.data.curindex=-1;
                            }

                          });

                      })
                      .catch(res => {
                          util.alert(res.message);
                      })
                      .finally(function (res) {
                          util.hideLoading();
                      });
                    }
                    else{
                      let remove = todos.splice(index, 1)[0]
                      that.setData({
                        todos: todos
                      })

                      if(index == that.data.curindex){
                       that.data.curindex=-1;
                      }
                    }
                  },
                  onCancel(e) {
                    
                  }
                });

            }
            else if(res.tapIndex==0){
              that.data.curindex = index;
              wx.navigateTo({
                  url: '../team/editgroup'
              })
            }
        }
    });
  },
  addgroup:function(){
    this.data.curindex = -1;
    wx.navigateTo({
        url: '../team/editgroup'
    })

  }

    ,mapqd:function(){
        wx.chooseLocation({
            type:"gcj02",
            success: function(res){
                that.setData({
                    'form.qdlat': res.latitude,
                    'form.qdlng': res.longitude,
                    'form.qdname':res.name,
                    'form.qdaddr':res.address
                })
            },
            fail: function() {
                // fail
            },
            complete: function() {
                // complete
            }
        })
    }
    ,mapzd:function(){
        wx.chooseLocation({
            type:"gcj02",
            success: function(res){
                that.setData({
                    'form.zdlat': res.latitude,
                    'form.zdlng': res.longitude,
                    'form.zdname':res.name,
                    'form.zdaddr':res.address
                })
            },
            fail: function() {
                // fail
            },
            complete: function() {
                // complete
            }
        })
    },
   
    binddura: function(e) {
        this.setData({
            'form.dura': that.data.arrdura[e.detail.value]
        })
    },
    bindzddura: function(e) {
        this.setData({
            'form.zddura': that.data.arrzddura[e.detail.value]
        })
    },
    bindtype: function(e) {
        this.setData({
            'form.type': e.detail.value
        })
    },
    //计算天数差的函数，通用  
    DateDiff : function(sDate1,  sDate2){    //sDate1和sDate2是2002-12-18格式  
       var  aDate,  oDate1,  oDate2,  iDays  
       aDate  =  sDate1.split("-")  
       oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])    //转换为12-18-2002格式  
        aDate  =  sDate2.split("-")  
        oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  
        iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24)    //把相差的毫秒数转换为天数  
        return  iDays  
     }
})